<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布订阅者</title>
</head>
<body>
    <script>
        // 事件触发器
        class EventEmiter{
            constructor(){
                // { eventType: [ handler1, handler2 ] }
                this.subs = Object.create(null)
                console.log(this.subs)
            }
            //注册事件 (订阅消息)
            $on(eventType,handler){
              this.subs[eventType] = this.subs[eventType] || []
              this.subs[eventType].push(handler)
            }
            //触发事件 (发布消息)
            $emit(eventType){
               if(this.subs[eventType]){
                this.subs[eventType].forEach(handler => {
                    handler()
                });
               }
            }
        }
        // 测试
        const em = new EventEmiter()
        // 注册事件
        em.$on("click",()=>{
            console.log("click1")
        })
        em.$on("click",()=>{
            console.log("click2")
        })
        // 触发事件
        em.$emit("click")
    </script>
</body>
</html>